MONTH_ABBR = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
              'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']

def handle_avh(command):
    if command.startswith("AVH:PEKLAX"):
        return """\
航班信息：
-------------------------------------------
航司 | 航班号 | 出发时间 | 到达时间 | 舱等 | 机型
-------------------------------------------
CA   | CA987  | 08:30     | 08:55+1  | Y   | 777
MU   | MU583  | 13:00     | 13:20+1  | Y   | 787
-------------------------------------------
"""
    else:
        return "暂不支持该指令。"

def handle_xs_fsi(command):
    if command.startswith("XS FSI/CX"):
        return """\
CX 航班时刻表：
---------------------------------------------
CX880 | HKG-LAX | 01JUN | 起飞 00:25 | 到达 21:55
CX981 | PEK-HKG | 01JUN | 起飞 14:00 | 到达 17:25
---------------------------------------------
"""
    else:
        return "暂不支持该日期或航司。"

import re
from datetime import datetime
import json
import os

def load_city_code_map():
    """自动加载城市三字码映射"""
    city_code_map = {}
    base_dir = os.path.dirname(os.path.abspath(__file__))
    # 加载国内
    try:
        with open(os.path.join(base_dir, 'gn-city-code.json'), encoding='utf-8') as f:
            data = json.load(f)
            for item in data.get('domestic_china', {}).get('airports', []):
                city = item.get('city_zh')
                code = item.get('iata_code')
                if city and code:
                    for c in code.split('/'):
                        c = c.strip().upper()
                        if len(c) == 3 and c.isalpha():
                            city_code_map[city.replace('（', '(').replace('）', ')')] = c
    except Exception:
        pass  # 数据文件可能不存在，忽略异常
    # 加载国际
    try:
        with open(os.path.join(base_dir, 'gj-city-code.json'), encoding='utf-8') as f:
            data = json.load(f)
            for country in data.get('countries', {}).values():
                for item in country.get('airports', []):
                    city = item.get('city_zh')
                    code = item.get('iata_code')
                    if city and code and city not in city_code_map:
                        for c in code.split('/'):
                            c = c.strip().upper()
                            if len(c) == 3 and c.isalpha():
                                city_code_map[city.replace('（', '(').replace('）', ')')] = c
    except Exception:
        pass
    return city_code_map

city_code_map = load_city_code_map()

def build_iata_to_city_map(city_code_map):
    """构建三字码到城市中文名的反向映射"""
    iata_to_city_map = {}
    for city, code in city_code_map.items():
        for c in code.split('/'):
            c = c.strip().upper()
            if len(c) == 3 and c.isalpha():
                if c not in iata_to_city_map:
                    iata_to_city_map[c] = city
    return iata_to_city_map

iata_to_city_map = build_iata_to_city_map(city_code_map)

def parse_eterm_input(text):
    """解析输入内容，返回 ETERM 格式"""
    found_cities = []
    used_pos = set()
    for city in city_code_map:
        pos = text.find(city)
        if pos != -1 and pos not in used_pos:
            found_cities.append((pos, city))
            used_pos.add(pos)
        elif city.startswith(text) or city.replace('/', '').startswith(text):
            found_cities.append((0, city))
    found_cities = [city for idx, city in sorted(found_cities)]
    # 查找日期
    date_match = re.search(r'(\d{1,2})[月\-/.](\d{1,2})[日号]?', text)
    year_match = re.search(r'(\d{4})年', text)
    day_str = month_str = year_str = None
    if date_match:
        month_str, day_str = date_match.groups()
    if year_match:
        year_str = year_match.group(1)
    result = []
    # 城市三字码
    if len(found_cities) >= 2:
        result.append(''.join([city_code_map[c] for c in found_cities[:2]]))
    elif len(found_cities) == 1:
        result.append(city_code_map[found_cities[0]])
    # 日期
    if day_str and month_str:
        try:
            if year_str:
                date_obj = datetime.strptime(f"{year_str}-{month_str}-{day_str}", "%Y-%m-%d")
                date_fmt = date_obj.strftime("%d%b%y").upper()
            else:
                date_obj = datetime.strptime(f"2024-{month_str}-{day_str}", "%Y-%m-%d")
                date_fmt = date_obj.strftime("%d%b").upper()
            result.append(date_fmt)
        except Exception:
            pass
    return ' '.join(result) if result else "无法解析输入内容"

def parse_chinese_date_to_eterm(text):
    """支持“2024年9月24”或“2024年9月24日”，以及“9月24”"""
    match = re.match(r"^(\d{4})年(\d{1,2})月(\d{1,2})日?$", text.strip())
    if match:
        year, month, day = match.groups()
        month_idx = int(month) - 1
        if 0 <= month_idx < 12:
            return f"{int(day):02d}{MONTH_ABBR[month_idx]}{str(year)[-2:]}"
    match = re.match(r"^(\d{1,2})月(\d{1,2})$", text.strip())
    if match:
        month, day = match.groups()
        month_idx = int(month) - 1
        if 0 <= month_idx < 12:
            return f"{int(day):02d}{MONTH_ABBR[month_idx]}"
    return None

def main():
    print("欢迎使用模拟 ETERM 终端系统（Ctrl+C 退出）")
    while True:
        cmd = input("\n输入指令：").strip()
        upper_cmd = cmd.upper()
        # 优先判断是否为仅日期输入，如“9月24”或“2024年9月24”
        date_eterm = parse_chinese_date_to_eterm(cmd)
        if date_eterm:
            print(date_eterm)
            continue
        if upper_cmd.startswith("AVH:"):
            print(handle_avh(upper_cmd))
        elif upper_cmd.startswith("XS FSI"):
            print(handle_xs_fsi(upper_cmd))
        # 支持连续多个三字码、空格分隔三字码时反查城市名
        elif all(x.isalpha() or x.isspace() for x in cmd) and len(upper_cmd.replace(' ', '')) % 3 == 0:
            codes = [c.strip().upper() for c in re.split(r'\s+', cmd) if c.strip()]
            result = []
            if len(codes) == 1 and len(codes[0]) > 3:
                for i in range(0, len(codes[0]), 3):
                    code = codes[0][i:i+3]
                    city = iata_to_city_map.get(code, code)
                    result.append(city)
            else:
                for code in codes:
                    if len(code) == 3:
                        city = iata_to_city_map.get(code, code)
                        result.append(city)
            print(''.join(result))
        # 中文输入支持空格和/，每个城市只取最后一个机场代码
        elif re.search(r'[\u4e00-\u9fa5/（）()]+', cmd):
            city_names = [name.strip() for name in re.split(r'\s+', cmd) if name.strip()]
            code_result = []
            for city in city_names:
                if '/' in city:
                    parts = city.split('/')
                    code = city_code_map.get(city)
                    if not code:
                        code = city_code_map.get(parts[-1], city)
                else:
                    code = city_code_map.get(city, city)
                if code and '/' in code:
                    code = code.split('/')[-1]
                code_result.append(code)
            print(' '.join(code_result))
        else:
            print("暂不支持该指令或格式，请重新输入。")

if __name__ == "__main__":
    main()
